﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Ymatou.API.Order.Model;
using Ymatou.API.Order.Model.Enums;
using Ymatou.API.Order.Model.OrderRequest;
using Ymatou.API.Order.Model.Response.AppResponse;
using Ymatou.CommonService;
using Ymatou.Evaluate.Entity;
using Ymatou.Evaluate.Seller.Model.ApiModel.Request.Query;
using Ymatou.Evaluate.Seller.Model.ApiModel.Response.Query;
using Ymatou.Evaluate.Seller.Model.Dto;
using Ymatou.ServiceCenter;

namespace Ymatou.Evaluate.Service.Seller.Implement
{
    /// <summary>
    /// 卖家评论查询
    /// </summary>
    public class SellerQueryService
    {
        /// <summary>
        /// 根据商品名称获取商品id列表
        /// </summary>
        /// <param name="sellerid"></param>
        /// <param name="productname"></param>
        /// <param name="maxCount"></param>
        /// <returns></returns>
        public GetOrderProductsByNameResponse GetOrderProductsByName(int sellerid, string productname, int? maxCount)
        {
            var resultresp = new GetOrderProductsByNameResponse();
            int totalcount = maxCount.HasValue
                ? maxCount.Value
                : 100;
            if (string.IsNullOrWhiteSpace(productname))
            {
                throw new BussniessException("1001", "商品名称不能为空");
            }
            var productqueryreq = new GetOrderProductsReq()
            {
                ProductName = productname,
                SellerId = sellerid,
                TradingStatus = (int) OrderStatusEnum.Received,
            };
            ApplicationLog.Debug(string.Format("GetOrderProductsReq调用获取商品id列表接口请求参数:{0}",
                JsonConvert.SerializeObject(productqueryreq)));
            try
            {

                var response =
                    ServiceClient.Execute<GetOrderProductsReq, BaseResponseModel<GetOrderProductsResp>>(productqueryreq);
                if (response != null && response.RetData != null && response.RetData.ProductInfoList != null)
                {
                    var reponsedata = response.RetData.ProductInfoList;
                    resultresp.TotalCount = reponsedata.Count > totalcount
                        ? totalcount
                        : reponsedata.Count;
                    var temlist = reponsedata;
                    if (temlist.Count > totalcount)
                    {
                        resultresp.TotalCount = totalcount;
                        resultresp.ProductList =
                            temlist.Take(totalcount).ToList().ConvertAll(input => new OrderProduct()
                            {
                                ProductId = input.ProductId,
                                ProductName = input.ProductTile
                            });
                    }
                    else
                    {
                        resultresp.TotalCount = temlist.Count;
                        resultresp.ProductList =
                            temlist.ToList().ConvertAll(input => new OrderProduct()
                            {
                                ProductId = input.ProductId,
                                ProductName = input.ProductTile
                            });
                    }

                    return resultresp;
                }
            }
            catch (Exception ex)
            {

                ApplicationLog.Error("GetOrderProductsReq调用获取商品id列表", ex);
                throw new BussniessException("2001", string.Format("调用获取商品id列表出错{0}", ex.Message));

            }
            return new GetOrderProductsByNameResponse()
            {
                ProductList = new List<OrderProduct>(),
                TotalCount = 0
            };

        }

        /// <summary>
        /// 根据评分获取总数
        /// </summary>
        /// <param name="sellerid"></param>
        /// <param name="score"></param>
        /// <returns></returns>
        public GetEvaluateCountResponse GetEvaluateCount(int sellerid, decimal score)
        {
            var resultresp = new GetEvaluateCountResponse();

            ApplicationLog.Debug(string.Format("GetEvaluateCount根据评分获取总数口请求参数:{0},{1}", sellerid, score));
            try
            {
                var endtime = DateTime.Now;
                var begintime = endtime.AddDays(-60);
                var ent = new QueryService().GetEvaluateCount(sellerid, score, begintime, endtime);
                if (ent != null)
                {
                    return new GetEvaluateCountResponse()
                    {
                        TotalCount = ent.TotalCount,
                        Score = ent.Score,
                        ScoreCount = ent.ScoreCount
                    };
                }
                return new GetEvaluateCountResponse()
                {
                    Score = score,
                    TotalCount = 0,
                    ScoreCount = 0
                };
            }
            catch (Exception ex)
            {

                ApplicationLog.Error("GetEvaluateCount根据评分获取总数", ex);
                throw new BussniessException("2001", string.Format("根据评分获取总数{0}", ex.Message));

            }
        }

        public GetEvaluateListResponse GetEvaluateList(GetEvaluateListRequest request)
        {
            var queryService = new QueryService();
            var response = new GetEvaluateListResponse
            {
                PageIndex = request.PageIndex,
                PageSize = request.PageSize,
                TotalCount = 0,
                ProductEvalList = new List<ProductEvaluate>()
            };

            List<EvaluateImgs> imgs;
            List<EvaluateReply> replies;
            int totalCount;
            var list = queryService.GetEvaluateProductList(new BaseQueryCondition
            {
                SellerId = request.SellerId,
                ProductId = request.ProductId,
                BeginTime = request.BeginTime,
                EndTime = request.EndTime,
                PageIndex = request.PageIndex,
                PageSize = request.PageSize,
                ScoreList = request.ScoreList,
                IsDeleted = request.IsDeleted
            }, out totalCount, out imgs, out replies);

            response.TotalCount = totalCount;
            if (list != null && list.Any())
            {
                var orderIds = list.Select(i => i.OrderId).Distinct().ToList();
                var productIds = list.Select(i => i.ProductId).Distinct().ToList();
                var buyerIds = list.Select(i => i.BuyerId).Distinct().ToList();

                var users = new Dictionary<int, string>();
                var orders = new List<EvaluateOrder>();
                var products = new List<Tuple<string, string, string>>();

                var taskParent = new Task(() =>
                {
                    #region 查询用户
                    var taskQueryUsers = new Task(() =>
                    {
                        users = queryService.GetUserLoginIdByUserIds(buyerIds);
                    }, TaskCreationOptions.AttachedToParent);
                    taskQueryUsers.Start();
                    #endregion

                    #region 查询订单

                    var taskQueryOrders = new Task(() =>
                    {
                        orders = queryService.GetEvaluateOrderByOrderIds(orderIds).ToList();
                       
                    }, TaskCreationOptions.AttachedToParent);

                    taskQueryOrders.Start();
                    #endregion

                    #region 查询商品

                    var taskQueryProduct = new Task(() =>
                    {
                        products = queryService.GetProductInfoByProductIds(productIds).ToList();

                    }, TaskCreationOptions.AttachedToParent);

                    taskQueryProduct.Start();
                    #endregion
                });

                taskParent.Start();
                taskParent.Wait();
                
                list.ForEach(item => response.ProductEvalList.Add(GetProductEvaluate(item, imgs, replies, users, orders, products)));
            }

            return response;
        }

        private ProductEvaluate GetProductEvaluate(EvaluateProduct item,
            IEnumerable<EvaluateImgs> imgs,
            IEnumerable<EvaluateReply> replies, Dictionary<int, string> users, IEnumerable<EvaluateOrder> orders,
            IEnumerable<Tuple<string, string, string>> products)
        {
            var prodEval = new ProductEvaluate
            {
                ProductId = item.ProductId,
                Score = item.Score,
                CatalogDesc = item.CatalogDesc??"",
                OrderId = item.OrderId,
                BuyerId = item.BuyerId,
                BuyerName = users.ContainsKey(item.BuyerId) ? users[item.BuyerId] : string.Empty,
                IsDeleted = item.IsDeleted,
                IsReplyed = item.HasReply,
                Comments = item.Comments,
                EvalTime = item.ProdEvalTime,
                ProdEvalId = item.ProdEvalId,
                Imgs =
                    imgs == null
                        ? new List<string>()
                        : imgs.Where(i => i.ProdEvalId == item.ProdEvalId)
                            .Select(i => i.ImgUrl)
                            .ToList(),
                ReplyComments = string.Empty,
                ReplyEvalTime = null
            };

            if (replies != null)
            {
                var reply = replies.FirstOrDefault(r => r.ProdEvalId == item.ProdEvalId);
                if (reply != null)
                {
                    prodEval.ReplyComments = reply.Reply;
                    prodEval.ReplyEvalTime = reply.ReplyTime;
                }
            }

            if (orders != null)
            {
                var orderEval = orders.FirstOrDefault(o => o.OrderId == item.OrderId);
                if (orderEval != null)
                {
                    prodEval.ServiceScore = orderEval.ServiceScore;
                    prodEval.LogisticsScore = orderEval.LogisticsScore;
                    prodEval.EvaluateWay =
                        orderEval.Way == EvaluateWay.Auto
                            ? EvaluateWayEnum.SysDefault
                            : EvaluateWayEnum.Buyer;
                }
            }

            if (products != null)
            {
                var product = products.FirstOrDefault(p => p.Item1.Equals(item.ProductId));
                if (product != null)
                {
                    prodEval.ProductName = string.IsNullOrWhiteSpace(product.Item2) ? string.Empty : product.Item2;
                    prodEval.ProductImg = string.IsNullOrWhiteSpace(product.Item3) ? string.Empty : product.Item3;
                }
                else
                {
                    prodEval.ProductName = string.Empty;
                    prodEval.ProductImg = string.Empty;
                }
            }

            return prodEval;
        }

        
    }

}